import 'package:flutter/material.dart';
import 'package:jm_flutter_common/jm_flutter_common.dart';
import '../../../../common/servers/api.dart';
import '../../../../common/utils/share.dart';
import '../../../../common/utils/shortcut.dart';
import '../../../../common/utils/show.dart';
import '../../../../config.dart';
import '../../../ui.dart';
import 'log_item.dart';

const String _uploadLogUrl = "http://lm.udubeauty.com:9062/hello/upload-log";
const String _uploadLogUrl2 = "http://114.132.40.227:9062/hello/upload-log";

//上传日志到服务器
Future<String?> jmUploadLog({
  String? url,
  String? appName,
}) async {
  url ??= _uploadLogUrl;
  appName ??= JmConfig.appName;
  //Show.loading();
  //await wait(300);
  //logd("uploadLog", "url: $url, appName: $appName");
  final date = DateTime.now();
  final logId = (date.millisecondsSinceEpoch - 1700000000000).toString();
  final fileName = "${date.toZh_y_mo_d_h_m}-$logId.log";

  final file =
      await JmLog.saveLog(filePath: "${JmConfig.appDocPath}/$fileName");
  //await wait(50);
  logd("uploadLog", "file: ${file.path}");
  try {
    final res = await Api.upload(url, file.path, fileName, body: {
      "appName": appName,
      "logId": logId,
    });

    if (res != null && res.statusCode == 200) {
      return logId;
    }

    logd("uploadLog", "path error: $res");
    final res2 = await Api.upload(_uploadLogUrl2, file.path, fileName, body: {
      "appName": appName,
      "logId": logId,
    });

    if (res2 != null && res2.statusCode == 200) {
      return logId;
    }

    logw("uploadLog", "path2 error: $res2");

    file.delete();

    return null;
    //判断是否上传成功
  } catch (e) {
    logw("uploadLog", "error: $e");

    return null;
  } finally {
    file.delete();
  }
}

class LogWidget extends StatefulWidget {
  final double height;
  final Color? color;
  final bool? showTime;
  final LogLevel? logLevel;
  final ValueChanged<String>? onLogShare;

  final ValueChanged<LogLevel>? onLogLevelChanged;
  final ValueChanged<bool>? onShowTimeChanged;

  const LogWidget(
      {Key? key,
      this.height = 200,
      this.color,
      this.showTime,
      this.logLevel,
      this.onLogLevelChanged,
      this.onShowTimeChanged,
      this.onLogShare})
      : super(key: key);

  @override
  State<LogWidget> createState() => _LogWidgetState();
}

class _LogWidgetState extends State<LogWidget> {
  final ScrollController scrollController = ScrollController();

  bool showTime = false;
  LogLevel logLevel = LogLevel.verbose;

  @override
  void initState() {
    // TODO: implement initState
    showTime = widget.showTime ?? false;
    logLevel = widget.logLevel ?? LogLevel.verbose;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.color ?? Colors.black,
      //padding: const EdgeInsets.only(left: 8, right: 8, top: 2, bottom: 2),
      width: double.infinity,
      alignment: Alignment.topLeft,
      child: SafeArea(
        top: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                MyText(
                  "运行日志",
                  size: 14,
                  color: Colors.white70,
                  i18n: false,
                ),
                const Spacer(),
                //筛选按钮ICon

                MyPullDownButton(
                  selectedIndex: logLevel.index,
                  itemLabels: const [
                    "Off",
                    "Fatal",
                    "Error",
                    "Warn",
                    "Debug",
                    "Verbose",
                  ],
                  child: const Padding(
                    padding: EdgeInsets.all(12),
                    child: MySvg(
                      "assets/svg/filter.svg",
                      package: "jm_flutter",
                      color: Colors.white,
                      width: 22,
                    ),
                  ),
                  onSelected: (index) {
                    logLevel = LogLevel.values[index];
                    setState(() {});
                    widget.onLogLevelChanged?.call(logLevel);
                  },
                ),
                IconButton(
                    icon: const Icon(
                      CupIcons.cloud_upload,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      Show.loading();
                      final logId = await jmUploadLog();
                      Show.dismiss();
                      logd("uploadLog", "logId: $logId");
                      if (logId != null) {
                        MyDialog(
                          title: "日志上传成功",
                          content: "日志ID: $logId",
                          actions: [
                            MyDialogAction.confirm(onTap: () {
                              back();
                            }),
                          ],
                        ).show();
                      } else {
                        Show.toast("日志上传失败");
                      }
                    }),
                IconButton(
                    icon: Icon(
                      CupIcons.time,
                      color: showTime ? Colors.white : Colors.white38,
                    ),
                    onPressed: () {
                      showTime = !showTime;
                      setState(() {});
                      widget.onShowTimeChanged?.call(showTime);
                    }),
                IconButton(
                    icon: const Icon(
                      CupIcons.share,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      JmLog.saveLog(
                              filePath:
                                  "${JmConfig.appDocPath}/${DateTime.now().toZhFull}.log")
                          .then((file) async {
                        widget.onLogShare?.call(file.path);
                        if (kIsWindows) {
                          return;
                        }

                        await Share.shareXFiles([XFile(file.path)]);
                        //file.delete();
                      });
                    }),
                IconButton(
                    icon: const Icon(
                      CupIcons.delete,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      setState(() {
                        JmLog.clear();
                      });
                    }),
                IconButton(
                  icon: const Icon(
                    CupIcons.arrow_down_to_line,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    scrollController.animateTo(0,
                        duration: const Duration(milliseconds: 200),
                        curve: Curves.ease);
                  },
                ),
              ],
            ),
            Expanded(
              child: StreamBuilder<bool>(
                  stream: JmLog.logStream,
                  builder: (context, snapshot) {
                    return Container(
                      alignment: Alignment.topCenter,
                      child: ListView.builder(
                        shrinkWrap: true,
                        padding: const EdgeInsets.only(top: 4, bottom: 4),
                        reverse: true,
                        itemBuilder: (context, index) {
                          final log =
                              JmLog.logList[JmLog.logList.length - 1 - index];

                          if (log.level.index > logLevel.index) {
                            return const SizedBox();
                          }
                          return JmLogDescItem(
                            logDesc: log,
                            showTime: showTime,
                          );
                        },
                        itemCount: JmLog.logList.length,
                        controller: scrollController,
                        physics: const BouncingScrollPhysics(),
                      ),
                    );
                  }),
            ),
          ],
        ),
      ),
    );
  }
}
